package com.five.mobile.controller;


import com.five.admin.dto.UserThreadLocalDto;
import com.five.admin.threadLocal.UserThreadLocal;
import com.five.core.result.Result;
import com.five.pojo.entity.Address;
import com.five.service.AddressRpcService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;


@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    private RedisTemplate redisTemplate;

    @DubboReference
    private AddressRpcService addressRpcService;


    @RequestMapping(value = "/queryAddress", method = RequestMethod.GET)
    public Result queryAddressById(HttpServletRequest request) {
        //获取roken
        Long id1 = UserThreadLocal.get().getId();
        //根据登录的用户获取id
        List<Address> addresses = addressRpcService.queryAddressById(id1);
        return Result.buildSuccess(addresses);
    }

    @RequestMapping(value = "/queryOne", method = RequestMethod.GET)
    public Result queryOne(Long id) {
        System.err.println("queryOne---"+id);
        Address one = addressRpcService.queryOne(id);
        return Result.buildSuccess(one);
    }

    /**
     * 修改
     * @param address
     * @return
     */
    @RequestMapping(value = "/updateAddress", method = RequestMethod.POST)
    public Result updateAddressById(@RequestBody Address address) {
        boolean update = addressRpcService.updateAddressById(address);
        return Result.buildSuccess(update);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteAddress", method = RequestMethod.GET)
    public Result deleteAddressById(Long id) {
        boolean delete = addressRpcService.deleteAddressById(id);
        return Result.buildSuccess(delete);
    }

    /**
     * 新增
     * @param address
     * @return
     */
    @RequestMapping(value = "/saveAddress", method = RequestMethod.POST)
    public Result saveAddress(@RequestBody Address address) {
        UserThreadLocalDto userThreadLocalDto = UserThreadLocal.get();
        address.setUserId(userThreadLocalDto.getId());
        boolean save = addressRpcService.saveAddress(address);
        return Result.buildSuccess(save);
    }

    @RequestMapping(value = "/queryDefaultAddress",method = RequestMethod.GET)
    public Result QueryDefaultAddress(){
        Long userId = UserThreadLocal.get().getId();
        Address defaultAddress = addressRpcService.findDefaultAddress(userId);
        return defaultAddress==null?Result.buildFail("没有默认地址"):Result.buildSuccess(defaultAddress);
    }
}
